"""
绘图脚本
- 调用 utils/plot_style.py 的字体与风格设置函数
"""

import matplotlib.pyplot as plt
from utils.plot_style import setup_chinese_font, set_plot_style
from src.core_utils import ensure_dir, save_figure, show_all_images
import os
import yaml
from PIL import Image

# 读取 config.yaml 参数
with open("config.yaml", "r", encoding="utf-8") as f:
    config = yaml.safe_load(f)

def plot_radar_chart(mean_table, score_fields, years, save_path=None, figsize=(7,7), font_family="Heiti TC"):
    """
    mean_table: DataFrame, index为年份，列为score_fields
    years: 要展示的年份列表
    figsize: 雷达图尺寸
    font_family: 中文字体
    """
    import numpy as np
    import matplotlib.pyplot as plt
    labels = score_fields
    num_vars = len(labels)
    angles = np.linspace(0, 2 * np.pi, num_vars, endpoint=False).tolist()
    angles += angles[:1]  # 闭合

    fig, ax = plt.subplots(figsize=figsize, subplot_kw=dict(polar=True))
    colors = ['#1f77b4', '#ff7f0e', '#2ca02c']

    for idx, year in enumerate(years):
        values = mean_table.loc[year, labels].tolist()
        values += values[:1]
        ax.plot(angles, values, label=str(year), color=colors[idx % len(colors)], linewidth=2)
        ax.fill(angles, values, color=colors[idx % len(colors)], alpha=0.15)

    ax.set_theta_offset(np.pi / 2)
    ax.set_theta_direction(-1)
    ax.set_thetagrids(np.degrees(angles[:-1]), labels)
    ax.set_title("三年四项计分均值雷达图", fontsize=16, fontfamily=font_family)
    ax.legend(loc='upper right', bbox_to_anchor=(1.2, 1.05))
    plt.tight_layout()
    if save_path:
        fig.savefig(save_path, dpi=300, bbox_inches='tight')
        print(f"雷达图已保存：{save_path}")
    plt.close(fig)

if __name__ == "__main__":
    # 设置中文字体和绘图风格
    setup_chinese_font()
    style_cfg = {
        'style': 'darkgrid',
        'dpi': 300,
        'figsize': [4, 3],  # 更小的图片尺寸
        'bbox_inches': 'tight'
    }
    set_plot_style(style_cfg)

    # 强制全局中文字体为 Heiti TC，防止中文乱码
    plt.rcParams['font.sans-serif'] = ['Heiti TC']
    plt.rcParams['axes.unicode_minus'] = False

    # 示例数据
    import pandas as pd
    score_fields = ['职业认知计分', '收入认知计分', '教育认知计分', '地位认知计分']
    years = [2020, 2021, 2022]
    mean_table = pd.DataFrame({
        '职业认知计分': [70, 72, 74],
        '收入认知计分': [60, 65, 68],
        '教育认知计分': [80, 82, 85],
        '地位认知计分': [55, 58, 60]
    }, index=years)
    radar_path = f"{config.get('figures_dir', 'figures')}/雷达图示例.png"
    plot_radar_chart(mean_table, score_fields, years, save_path=radar_path, figsize=(4, 3), font_family=config['plot']['font_family'])
    print(f"雷达图已保存：{radar_path}")

    # 示例数据
    x = [1, 2, 3, 4]
    y = [10, 20, 15, 25]

    plt.figure()
    plt.plot(x, y, marker='o')
    fontdict_title = {'family': config['plot']['font_family'], 'fontsize': 10}
    fontdict_label = {'family': config['plot']['font_family'], 'fontsize': 8}
    plt.title("中文标题示例", fontdict=fontdict_title)
    plt.xlabel("横轴：变量X", fontdict=fontdict_label)
    plt.ylabel("纵轴：变量Y", fontdict=fontdict_label)
    plt.grid(True)
    plt.tight_layout()
    img_filename = "plot_demo.png"
    img_path = save_figure(plt, img_filename)
